package com.mark.springbootredis.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mark.springbootredis.common.RequestWrapper;
import com.mark.springbootredis.request.LoginRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: MARK
 * @Date: 2019/8/20 11:21
 * @Version: 1.0.0
 * @Description: 登录拦截器 获取session信息 存到redis
 */
@Slf4j
@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if("/admin/login".equals(uri)){
            RequestWrapper requestWrapper = new RequestWrapper(request);
            String body = requestWrapper.getBody();
            log.info("body: " + body);
            // log.info("stringRedisTemplate: " + stringRedisTemplate);
            //json转对象
            LoginRequest loginRequest = JSON.parseObject(body, LoginRequest.class);
            String username = loginRequest.getUsername();
            log.info("用户名" + username);
            //从redis读取数据
            log.info("intercept从redis读取数据");
            String result = stringRedisTemplate.opsForValue().get("username-" + username);
            log.info("从redis中取出的数据为: " + result);
            if (result == null) {
                log.info("未登录过");
            } else {
                log.info("登陆过");
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
